/*
 * Copyright © 2021 http://www.TestCopyright.com/ All rights reserved.
 */
package com.xjh;

import com.xjh.basestudy.javabase.classandinterface.Student;
import org.junit.Test;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： 徐建华
 * @date： 2021/11/24
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
public class testStream {
    @Test
    public void test1() {
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        map1.put("a", "1");
        map2.put("b", "2");
        map3.put("c", "3");
        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map1);
        list.add(map2);
        list.add(map3);
        System.out.println(list);//[{a=1}, {b=2}, {c=3}]
    }

    @Test
    public void test2() {
        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        map1.put("a", "1");
        map2.put("a", "2");
        map3.put("a", "3");
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> list2 = new ArrayList<>();
        list.add(map1);
        list.add(map2);
        list.add(map3);
        System.out.println(list);//[{a=1}, {a=2}, {a=3}]
//        stream流查找key为a，value为1的数据并返回?([{a=1}])
        List<Map<String, Object>> stream01 = list.stream()
                .filter(item -> item.get("a").equals("1"))
                .collect(Collectors.toList());
//   高级写法：抽离条件(item的类型是什么，泛型就是什么)
        Predicate<Map<String, Object>> predicate1 = item -> item.get("a").equals("1");
        List<Map<String, Object>> stream02 = list.stream()
                .filter(predicate1)
                .collect(Collectors.toList());

        System.out.println(stream01);
        System.out.println(stream02);
    }


    @Test
    public void test3() {
        //需求1: 计算某个集合中 数值之和
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        System.out.println(list.stream()
//                将所有元素相加
//                .reduce(0, (x, y) -> x + y));
//                将每个元素+10,如果用filter会报错，filter只能过滤元素，而不能操作元素的值
//                .map(item->item+10).collect(Collectors.toList())
//                使用filter过滤出偶数,如果这里使用map，则返回的是10个true或者false
                 .filter(item->item % 2 == 0).collect(Collectors.toList())
        );

    }

    @Test
    public void test4() {
        Student student = null;
        //使用 throw抛异常
        if (student == null) {
            throw new IllegalArgumentException("用户不存在.");
        }
        // 优雅的方式：使用断言抛异常
        //Assert.notNull(student, "用户不存在.");
    }

}
